<?php
/**
 * @property JobGroup $JobGroup
 * @property SessionComponent $Session
 */
class JobGroupsController extends AppController {

	var $name = 'JobGroups';
  
  var $helpers = array('Js', 'MyForm', 'Elfinder', 'Tooltip');
  
  var $flashMessages = array(); // Prob not using this now - using AppController::addFlashMsg() instead
  var $flashMsgGlue  = " ";
  
  
  
  // ---------------------------------------------------------------------------------------
  
  /**
   * INDEX
   */
	function index() {
		$this->JobGroup->recursive = 0;
		$this->set('jobGroups', $this->paginate());
	}

  /**
   * VIEW
   * 
   * View a single JobGroup and a list of its Jobs. User then can edit/delete a Job from the list.
   */
	function view($id = null) {
    
		if (!$id) {
			//$this->Session->setFlash('Invalid job group id provided to JobGroupsController::view()');
      $this->addFlashMsg('Invalid job group id provided to JobGroupsController::view()', $this->flashError);
			$this->redirect(array('action' => 'index'));
		}
    
    $jobs = $this->JobGroup->Job->find('all', array('conditions'=>array('Job.job_group_id'=>$id)));
    
    $this->set('jobs', $jobs);
		$this->set('jobGroup', $this->JobGroup->read(null, $id));
	} //////////// end view() //////////////////////////

  
  
  
  
  
  
/*  
//  

//	function add() {
//    
//		if (!empty($this->data)) {
//	
//      $this->JobGroup->create();
//			
//      if($this->JobGroup->saveAll($this->data, array('validate'=>'first'))) {
//        
//				$this->Session->setFlash('The job group has been saved to the database.');
//				$this->redirect(array('action' => 'index'));
//			} 
//      else {
//				$this->Session->setFlash('The job group could not be saved. Please, try again.');
//			}
//		}
//	} //////////// end add() ///////////////
//
//  
//	function edit($id = null) {
//		
//    if (!$id && empty($this->data)) {
//			$this->Session->setFlash(__('Invalid job group', true));
//			$this->redirect(array('action' => 'index'));
//		}   
//
//    // If ready to save data
//		if (!empty($this->data)) {
//			if ($this->JobGroup->saveAll($this->data, array('validate'=>'first'))) {
//				$this->Session->setFlash(__('The job group has been saved', true));
//				$this->redirect(array('action' => 'index'));
//			} 
//      else {
//				$this->Session->setFlash(__('The job group could not be saved. Please, try again.', true));
//			}
//		}
//    ///////////////////////////////////////////////////////////////
//    ////// When accessing new edit page ///////////////////////////
//		if (empty($this->data)) {
//			$this->data = $this->JobGroup->read(null, $id);
//		}
//	} //////// end edit() //////////////////
*/ 
  
  /**
   * Handles both adding a new JobGroup (and its optional associated models/fields) and editing
   * an existing JobGroup record (and its optoinal assoc models/fields).
   * 
   * @param int $id 
   */
  function form($id = null) {
    
    // SETUP STATE VARS
    $addNewGroup = true;
    $editGroup   = false;
    $validated = true;
    
    // Detect edit mode
    if($id != null) {
      $addNewGroup = false;
      $editGroup   = true;
    }
    
    /////////////////////////////////////////////////////////////////////////
    //// VALIDATE & SAVE DATA ///////////////////////////////////////////////  
    // <editor-fold defaultstate="collapsed" desc="Validate & Save data">
    if (!empty($this->data)) {
      //////////////////////////////////////////////////
      // Setup things before doing validating or saving, 
      //   such as removing blank Model fields from $data 
      $this->JobGroup->removeBlankOptionalFields($this->data, $editGroup);
      /////////////////////////////////
      // VALIDATE everything first...     
      $validated = true;
      $validated = $this->JobGroup->saveAll($this->data, array('validate' => 'only'));

      if (!$validated) {
            //$this->flashMessages[] = 'The job group did NOT validate! Please correct the marked fields.';
        $this->addFlashMsg('The job group did NOT validate! Please correct the marked fields.', $this->flashError);
      }
      ////////////////////////////////////
      // SAVE ALL if everything validated
      if ($validated) {
        if ($addNewGroup) {
          $this->JobGroup->create();
        }
        if ($this->JobGroup->saveAll($this->data, array('validate' => 'first'))) {

                //$this->flashMessages[] = 'The job group has been saved to the database.';
          $this->addFlashMsg('The job group has been saved to the database.', $this->flashSuccess);  
                /*
                if (count($this->flashMessages)) { // set the flash msgs now before the redirect
                  $this->setMyFlashMsgs();
                }*/
          $this->redirect(array('action' => 'index'));
        } 
        else {
          $msg = 'The job group could NOT be saved! There could be a database issue. Please try again.';
                //$this->flashMessages[] = $msg;
          $this->addFlashMsg($msg, $this->flashError);
        }
      } // end if everything validated
    } // end if there is data to be saved// </editor-fold>
        
    ////////////////////////////////////////////////////////////////////////////
    ////// When accessing new edit page (get data for view) ////////////////////
		if($editGroup) {
			//$this->data = $this->JobGroup->read(null, $id);

      // only get 'data' if brand new form (don't overwrite 'data' if form didn't 
      //   validate - keep user's entries for them)
      if(empty($this->data)) {
      $this->JobGroup->contain('JobGroupAltName');
      $this->data = $this->JobGroup->find('first', array('conditions' => array('JobGroup.id' => $id)));
      }
		}
    // ----------------------------------------------------------------------
    // Get a list of Job Group dir names (and their paths) that are not already in the database.
    $dirToInclude = $editGroup ? $this->JobGroup->getModelFieldValFromId("JobGroup", "name", $id) : null;
    $newGroupDirsAndFullPath = $this->getNewGroupDirsAndFullPath($dirToInclude);
    
    // -----------------
    // Send vars to view
    $this->set(compact('addNewGroup', 'editGroup', 'newGroupDirsAndFullPath', 'validated'));
      
          /*
          if(count($this->flashMessages)) {          
            $this->setMyFlashMsgs();
          }*/
  } ////////////////// end form() ////////////////////
  
  /** 
   * Returns a assoc array of new JobGroups (dirs in filesystem but not yet in db) and abs path info.
   * Returned array will be in form: $newGroupDirsAndInfo['dir'] = $abs_path.  This way the view
   * can iterate through it and get both the dir name and absolute path of the dir.
   *
   * @param string $dirToInclude  Possible dir name to include in the results even if it is already in db
   *                              (usefull when supplying data for and Edit view).
   */
  function getNewGroupDirsAndFullPath($dirToInclude = null) {
    
    $newGroupDirsAndFullPath = array();
    
    // First get a list of dirs in the Job Group dir, excluding any special dirs
    $dirsInGroupDir = $this->JobGroup->getDirNamesFromBase(GlobalsClass::getJobGroupFullPath() );
                                          // /* dir to exclude: */ GlobalsClass::getPreviewDirName());
    
    // Next, get list of new Job Group dirs (not already in database, 
    //   except if editing, then include the existing record's dir if it still exists)
    $newGroupDirs = $this->JobGroup->getNewOrOldDirNamesRelativeToDB($dirsInGroupDir, "name",
                                                                       true, $dirToInclude);

    foreach($newGroupDirs as $groupDir) {
      // the full path of this particular group dir
      $groupFullPath = GlobalsClass::getJobGroupFullPath() . DS . $groupDir;
      
      $newGroupDirsAndFullPath[$groupDir] = $groupFullPath;
    }
    
    return $newGroupDirsAndFullPath;
  } //////////// end getNewGroupDirsAndInfo() ////////////////////


   /**
   * DELETE
   */
	function delete($id = null) {
    $groupName = $this->JobGroup->getModelFieldValFromId("JobGroup", "name", $id);
    
		if (!$id) {
			//$this->Session->setFlash(__('Invalid id for job group', true));
      $this->addFlashMsg("Invalid id for job group", $this->flashError);
			$this->redirect(array('action'=>'index'));
		}
		if ($this->JobGroup->delete($id)) {
      $deletedMsg = "Job Group '$groupName' and all its Jobs and Job Versions have been deleted from the database.";
			//$this->Session->setFlash($deletedMsg);
      $this->addFlashMsg($deletedMsg, $this->flashSuccess );
			$this->redirect(array('action'=>'index'));
		}
		//$this->Session->setFlash('Job Group was NOT deleted. There could be a database or id problem. Try again.');
    $this->addFlashMsg('Job Group was NOT deleted. There could be a database or id problem. Try again.',
                            $this->flashError);
		$this->redirect(array('action' => 'index'));
	} //////////////// end delete() ///////////////////////////////
  
  
  
  
  
  
  /**
   * 
   */
  function setMyFlashMsgs() {
    
    $this->Session->setFlash(join($this->flashMsgGlue, $this->flashMessages));
  } ////// end setMyFlashMsgs() ///////////
  
  
  
  
}
